//
//  LGTabBarButton.m
//  微博
//
//  Created by MS on 15-12-3.
//  Copyright (c) 2015年 MS. All rights reserved.
//

#define ImageRidio 0.7
#import "LGTabBarButton.h"
#import "LGBadgeView.h"
#import "UIView+Frame.h"

@interface LGTabBarButton ()

@property (nonatomic,weak) LGBadgeView * badgeView;

@end

@implementation LGTabBarButton

// 重写setHighlighted，取消高亮做的事情
-(void)setHighlighted:(BOOL)highlighted{};

-(LGBadgeView *)badgeView
{
    if (!_badgeView) {
        LGBadgeView * tmp = [LGBadgeView buttonWithType:UIButtonTypeCustom];
        [self addSubview:tmp];
        _badgeView = tmp;
    }
    
    return _badgeView;
}


-(instancetype) initWithFrame:(CGRect)frame
{
    if (self =[super initWithFrame:frame]) {
        
        [self setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [self setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected];
        
        //图片居中
        self.imageView.contentMode = UIViewContentModeScaleAspectFit;
        //文字居中
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        //设置字体
        self.titleLabel.font = [UIFont systemFontOfSize:12];
        
    }
    
    return self;
}


-(void)setItem:(UITabBarItem *)item
{
    _item = item;
   
    //清空监听对象
    [self observeValueForKeyPath:nil ofObject:nil change:nil context:nil];
    
    [item addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    [item addObserver:self forKeyPath:@"image" options:NSKeyValueObservingOptionNew context:nil];
    [item addObserver:self forKeyPath:@"selectedImage" options:NSKeyValueObservingOptionNew context:nil];
    [item addObserver:self forKeyPath:@"badgeValue" options:NSKeyValueObservingOptionNew context:nil];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    
    [self setTitle:_item.title forState:UIControlStateNormal];
    [self setImage:_item.image forState:UIControlStateNormal];
    [self setImage:_item.selectedImage  forState:UIControlStateSelected];
    self.badgeView.badgeValue = _item.badgeValue;
}


-(void) layoutSubviews
{
    [super layoutSubviews];
    
    CGFloat imageX = 0;
    CGFloat imageY = 0;
    CGFloat imageW = self.bounds.size.width;
    CGFloat imageH = self.bounds.size.height*0.7;
    self.imageView.frame = CGRectMake(imageX, imageY, imageW, imageH);
    self.imageView.center = CGPointMake(imageW*0.5, imageH*0.5);
    
    CGFloat titleX = 0;
    CGFloat titleY = CGRectGetMaxY(self.imageView.frame)+2;
    CGFloat titleW = self.bounds.size.width;;
    CGFloat titleH = self.bounds.size.height-imageH-10;
    self.titleLabel.frame = CGRectMake(titleX, titleY, titleW, titleH);

    self.badgeView.x = self.width - self.badgeView.width - 10;
    self.badgeView.y = 0;

}


@end
